$(document).ready(function() {
    if ($("#miniBasketDisabledOrEnabledMvt").val() === "false") {
        // If the hidden field is false then return early out of the setup function, so none of the bindings are set up
        return;
    }
    //Add to Basket - MiniBag
    $("a.product_AddToBasket").click(function() {
        if (mini_basket_holder.addButtonDisabled === true) {
            return false;
        }

        var parentId = $("span.ctlSeparateProduct-parentId input").val();
        var colour = $("div.colour select option:selected").val();
        var sizeId = $("div.size-guide select option:selected").val();

        if (parentId.length > 0 && colour.length > 0 && sizeId.length > 0 && sizeId != -1) {
            mini_basket_holder.disableAddToBagButton();
            mini_basket_holder.scrollToTopOfPage();

            mini_basket_holder.srvAddBasketItem(parentId, colour, sizeId);
        }

        return false;
    });

    //Add Mix and Match to Basket - MiniBag
    $("a.product_AddSeparatesToBasket").click(function() {
        if (!CanSubmit() || mini_basket_holder.addButtonDisabled === true) {
            return false;
        }

        mini_basket_holder.disableAddToBagButton();
        mini_basket_holder.scrollToTopOfPage();

        strSeparates = createStringFromSeparates();
        mini_basket_holder.srvAddBasketItems(strSeparates);

        return false;
    });

    $('#miniBasket .next').click(function() {
        if ($('#miniBasket .next').hasClass('disabled')) {
            return false;
        } else {
            mini_basket_holder.nextPage();
            this.blur();
            return false;
        }
    });

    $('#miniBasket .prev').click(function() {
        if ($('#miniBasket .prev').hasClass('disabled')) {
            return false;
        } else {
            mini_basket_holder.prevPage();
            this.blur();
            return false;
        }
    });

    $('#miniBasket .save-for-later').click(function() {
        mini_basket_holder.srvSaveAllBasketItemsForLater();

        try {
            pageTracker._trackEvent('Mini Bag', 'Move Bag Item to Saved List');
        }
        catch (err) { }

        return false;
    });

    /*$('.remove').livequery('mouseenter', function() {
        $(this).parent().prev('div').addClass('hover-state');
    });

    $('.remove').livequery('mouseout', function() {
        var that = this;
        setTimeout(function() { $(that).parent().prev('div').removeClass('hover-state'); }, 1);
    });*/

    $('.closeAddToBasketLink').bind('click', function() {
        $('#addToBasketAlert').hide();
        $('#transp').hide();
        return false;
    });

    $('body').bind('click', function() {
        if ($('#addToBasketAlert_visibleType_success').css('display') == 'block') {
            $('#addToBasketAlert').hide();
        }
    });

    $('#addToBasketAlert').bind('click', function(event) {
        event.stopPropagation();
    });
    /*$(".remove").livequery("click", function() {
        $(this).parent().prev('.item').fadeOut();
        $(this).parent().fadeOut();
    });*/
    $('#minibagLinks .go-to-bag').click(function() {
        try {
            pageTracker._trackEvent('Mini Bag', 'Go to Bag');
        }
        catch (err) { }
    });
    $('#minibagLinks .proceed-to-checkout').click(function() {
        try {
            pageTracker._trackEvent('Mini Bag', 'Pay Now');
        }
        catch (err) { }
    });

    $('#miniBasket').bind('mouseenter', function() {
        if ($("#openMiniBasketOnHover").val() === "true") {
            mini_basket_holder.maximizeBasket(false);
        }
        if (!mini_basket_holder.basketLoadingOrHasLoaded) {
            mini_basket_holder.srvLoadBasketItems();
        }
    });
    $('#miniBasket').hover(function() {
        mini_basket_holder.isMouseOverMiniBasket = true;
    }, function() {
        mini_basket_holder.isMouseOverMiniBasket = false;
    });
});

/**
* Class for handling miniBasket
*
*/
function miniBasketHolder() {
    this.basketLoadingOrHasLoaded = false;
    this.products = [];
    this.qtyPerPage = 3;
    this.currPage = 1;
    this.qtyPage = 1;
    this.minimizing = false;
    this.maximized = false;
    this.paging = false;
    this.minimizeAfterAddTimeout = 4000;
    this.minimizeAfterMouseLeaveTimeout = 500;
    this.productAddedTimeout = this.minimizeAfterAddTimeout;
    this.minimiseBasketTimeout = null;
    this.currencyCodePrefix = "";
    this.currencyCodePostfix = "";
    this.totalPrice = 0;
    this.totalQuantity = 0;
    this.containsVoucher = false;
    this.errorMessageHideTimeout = null;
	this.openSpeed = 700;
	this.closeSpeed = 500;
	this.basketLoadInterruptedMessage = "Oops! Please try again";
	this.addInterruptedErrorMessage = "Oops! Sorry the product was not added to your bag, please try again";
	this.removeInterruptedErrorMessage = "Oops! Sorry the product was not removed from your bag, please try again";
	this.cannotAddGiftVoucherMessage = "Items can't be purchased with gift vouchers";
	this.couldNotSaveForLaterMessage = "Oops! Please try again";
	this.productPageAddedMessage = "Added to bag...";
	this.productRemovedMessage = "Removed from your bag...";
	this.messageText = "";
	this.messageIsNegative = false;
	this.addButtonDisabled = false;
	this.addButtonDisabledResetTimer = null;
	this.addButtonDisabledTimeout = 5000;
	this.itemTemplate = "";
	this.itemHighlight = "#d7d7d7";
	this.itemContainerHeight = 411;
	this.itemHeight = 137;
	this.isMouseOverMiniBasket = false;
}

miniBasketHolder.prototype.showViewSavedItemsButtonOnEmptyBag = function() {
    $('#miniBasket #viewSavedItems').removeClass("hide");
};

miniBasketHolder.prototype.ensureMiniBasketDependenciesHaveLoaded = function(dependenciesLoadedSuccessfullyCallback) {
    if (!this.basketLoadingOrHasLoaded) {
        $('#miniBasket .body.loading').show();
        TemplateLoader.load("/item.html", function(template) {
            mini_basket_holder.itemTemplate = template;
            dependenciesLoadedSuccessfullyCallback();
        }, mini_basket_holder.doError, mini_basket_holder.basketLoadInterruptedMessage);
    }
    else {
        dependenciesLoadedSuccessfullyCallback();
    }
    this.basketLoadingOrHasLoaded = true;
};

miniBasketHolder.prototype.enableAddToBagButton = function() {
    this.addButtonDisabled = false;
    clearTimeout(this.addButtonDisabledResetTimer);
};
miniBasketHolder.prototype.disableAddToBagButton = function() {
    this.addButtonDisabled = true;
    this.addButtonDisabledResetTimer = setTimeout(function() { mini_basket_holder.addButtonDisabled = false; }, this.addButtonDisabledTimeout);
};

miniBasketHolder.prototype.scrollToTopOfPage = function() {
    if (document.all && navigator.userAgent.indexOf("opera") == -1) {
        $('html').animate({ scrollTop: $(".site-wrapper").offset().top }, 500);
    } else {
        $('html, body').animate({ scrollTop: $(".site-wrapper").offset().top }, 500);
    }
};

miniBasketHolder.prototype.productAdded = function(messageText) {
    $('#miniBasketRemoved').hide();
    clearTimeout(this.productAddedHideTimeout);
    clearTimeout(this.productAddedSentenceHideTimeout);
    $('#miniBasket').addClass('productAdded');
    this.productAddedHideTimeout = setTimeout(function() { $('#miniBasket').removeClass('productAdded'); }, this.productAddedTimeout);
    if (messageText !== null && messageText.length > 0) {
        $('#miniBasketAdded').html(messageText).show();
        $(".add-to-bag-notification").addClass("saved").html(this.productPageAddedMessage).fadeIn(this.openSpeed);
    } else {
        $(".add-to-bag-notification").removeClass("saved").html("");
    }

    $(".item.true").animate({ backgroundColor: mini_basket_holder.itemHighlight }, this.openSpeed);
    this.productAddedSentenceHideTimeout = setTimeout(function() {
        $('#miniBasketAdded').hide("blind", {}, mini_basket_holder.closeSpeed);
        $(".item.true").animate({ backgroundColor: mini_basket_holder.itemHighlight }, mini_basket_holder.closeSpeed, function() {
            $(".item.true").css({"background-color" : "#FFFFFF"});
        });
        $(".add-to-bag-notification").fadeOut(mini_basket_holder.closeSpeed).removeClass("saved").html("");
    }, this.productAddedTimeout);
};

miniBasketHolder.prototype.productRemoved = function() {
    $('#miniBasketAdded').hide();
    clearTimeout(this.productAddedHideTimeout);
    $('#miniBasketRemoved').html(this.productRemovedMessage).fadeIn(this.openSpeed);
    clearTimeout(this.productAddedSentenceHideTimeout);
    $(".add-to-bag-notification").fadeOut(this.openSpeed);
    this.productAddedSentenceHideTimeout = setTimeout(function() {
        $('#miniBasketRemoved').hide("blind", {}, this.closeSpeed);
    }, this.productAddedTimeout);
};

miniBasketHolder.prototype.srvLoadBasketItems = function() {
    var self = this;
    var countryId = $('#hdnCountryId').val();
    self.ensureMiniBasketDependenciesHaveLoaded(function() {
        $.ajax({
            type: "POST",
            url: "http://" + location.host + "/services/srvBasket.asmx/GetAllBasketItems",
            data: "{CountryId: " + countryId + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                var basket = eval('(' + msg.d + ')');
                self.updateMiniBasketContent(basket);
                self.applyLayoutTemplate(basket);
            },
            error: function(xhr, status, e) {
                self.doError(self.basketLoadInterruptedMessage);
            }
        })
    });
};

miniBasketHolder.prototype.srvAddBasketItem = function(ParentId, Colour, SizeId) {
    var self = this;
    var countryId = $('#hdnCountryId').val();
    self.maximizeBasket(false);
    self.resetMinimiseAfterClick();
    self.ensureMiniBasketDependenciesHaveLoaded(function() {
        $.ajax({
            type: "POST",
            url: "http://" + location.host + "/services/srvBasket.asmx/AddInventoryToBasket",
            data: "{ParentId: " + ParentId + ", Colour: \"" + Colour + "\", SizeId: " + SizeId + ", CountryId: " + countryId + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                var basket = eval('(' + msg.d + ')');
                self.updateMiniBasketContent(basket);
                self.applyLayoutTemplate(basket);
                if (basket.ContainsVoucher) {
                    self.doError(self.cannotAddGiftVoucherMessage);
                } else if (self.messageIsNegative === true) {
                    self.doError(self.messageText);
                } else {
                    self.productAdded(self.messageText);
                }
                self.maximizeBasket(true);
                self.resetMinimiseAfterClick();
                self.updateMiniBasket(true);
                self.enableAddToBagButton();
            },
            error: function(xhr, status, e) {
                self.doError(self.addInterruptedErrorMessage);
                self.enableAddToBagButton();
            }
        })
    });
};

miniBasketHolder.prototype.srvAddBasketItems = function(strSeparates) {
    if (strSeparates === null || strSeparates.length === 0) {
        return;
    }

    var self = this;
    var countryId = $('#hdnCountryId').val();
    self.maximizeBasket(false);
    self.resetMinimiseAfterClick();
    self.ensureMiniBasketDependenciesHaveLoaded(function() {
        $.ajax({
            type: "POST",
            url: "http://" + location.host + "/services/srvBasket.asmx/AddInventorysToBasket",
            data: "{StrSeparates: '" + strSeparates + "', CountryId: " + countryId + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                var basket = eval('(' + msg.d + ')');
                self.updateMiniBasketContent(basket);
                self.applyLayoutTemplate(basket);
                if (basket.ContainsVoucher) {
                    self.doError(self.cannotAddGiftVoucherMessage);
                } else if (self.messageIsNegative === true) {
                    self.doError(self.messageText);
                } else {
                    self.productAdded(self.messageText);
                }
                self.maximizeBasket(true);
                self.resetMinimiseAfterClick();
                self.updateMiniBasket(true);
                self.enableAddToBagButton();
            },
            error: function(xhr, status, e) {
                self.doError(self.addInterruptedErrorMessage);
                self.enableAddToBagButton();
            }
        })
    });
};

miniBasketHolder.prototype.srvRemoveBasketItem = function(BasketItemId) {
    try {
        pageTracker._trackEvent('Mini Bag', 'Remove Bag Item');
    }
    catch (err) { }

    var self = this;
    self.resetMinimiseAfterClick();
    var countryId = $('#hdnCountryId').val();
    $.ajax({
        type: "POST",
        url: "http://" + location.host + "/services/srvBasket.asmx/DeleteInventoryFromBasket",
        data: "{BasketItemId: " + BasketItemId + ", CountryId: " + countryId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            self.updateMiniBasketContent(eval('(' + msg.d + ')'));
            self.resetMinimiseAfterClick();
            self.productRemoved();
            var positionalNumberOfFirstProductOnCurrentPage = ((self.currPage - 1) * self.qtyPerPage) + 1;
            if (positionalNumberOfFirstProductOnCurrentPage > self.totalDifferentProductsInBag && self.totalDifferentProductsInBag > 0) {
                self.prevPage();
            }
            self.doPageButtonVisibilities();
            self.maximizeBasket(true);
        },
        error: function(xhr, status, e) {
            self.doError(self.removeInterruptedErrorMessage);
            self.enableAddToBagButton();
        }
    });
};

miniBasketHolder.prototype.srvSaveAllBasketItemsForLater = function() {
    var self = this;
    $.ajax({
        type: "POST",
        url: "http://" + location.host + "/services/srvSaveForLater.asmx/SaveAllBasketItemsForLater",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            if (msg.d) {
                document.location = "/basket/pgebasket.aspx#your-saved-items";
            } else {
                self.doError(self.couldNotSaveForLater);
            }
        },
        error: function(xhr, status, e) {
            self.doError(self.couldNotSaveForLaterMessage);
        }
    });
};

miniBasketHolder.prototype.updateMiniBasketContent = function(miniBag) {
    $('#miniBasket .body.loading').hide();
    $('.mini-bag-title').removeClass('loading').addClass('loaded');

    this.currencyCodePrefix = miniBag.CurrencyPrefix;
    this.currencyCodePostfix = miniBag.CurrencyPostfix;
    this.totalPrice = miniBag.TotalPrice;
    this.totalQuantity = miniBag.TotalQuantity;
    this.containsVoucher = miniBag.ContainsVoucher;
    this.messageText = miniBag.MessageText;
    this.messageIsNegative = miniBag.MessageIsNegative;
    this.hasSaveForLaterItems = miniBag.HasSaveForLaterItems;

    /*NOTE- THIS LINE CAUSES THE BAG TO CLOSE before REOPENING
    this.minimizeBasket();*/

    this.products = miniBag.Entities;

    if (this.products.length > 0) {
        if ($('#mini-bag-body').is('.advert-enabled')) {
            $('#mini-bag-body').addClass("advert-space");
    }
    } else {
        if ($('#mini-bag-body').is('.advert-enabled')) {
            $('#mini-bag-body').removeClass("advert-space");
        }
    }
    if (this.hasSaveForLaterItems == true) {
        $('#viewSavedItems').removeClass("hide");
    } else {
        $('#viewSavedItems').addClass("hide");
    }

    this.updateMiniBasket(true);
};

miniBasketHolder.prototype.applyLayoutTemplate = function(itemData) {
    this.currPage = 1;
    var tpResult = TrimPath.parseTemplate(this.itemTemplate).process(itemData, null);
    $('#miniBasket .body.full .items').html(tpResult);
    $(".item.true").animate({ backgroundColor: mini_basket_holder.itemHighlight }, this.openSpeed);
};

miniBasketHolder.prototype.updateMiniBasket = function(doPosition) {
    this.qtyPage = 1;
    var total_diff_items = 0;
    var ind = 1;
    for (var i = 0; i < this.products.length; i++) {
        if (this.products[i] !== undefined) {
            total_diff_items++;

            try {
                if (this.products[i].IsSelectedItem && doPosition) {
                    var destPage = Math.ceil(ind / this.qtyPerPage);

                    var currTop = $('#miniBasket .itemsClmn').position().top;
                    var vis = $('#miniBasket .itemsClmn').is(":visible");
                    if (!vis) {
                        $('#miniBasket .itemsClmn').show();
                    }

                    var positionCurrPage = (currTop / mini_basket_holder.itemContainerHeight) + 1;

                    var desiredTop = -1 * (1 * currTop) - ((destPage - positionCurrPage) * mini_basket_holder.itemContainerHeight);

                    clearTimeout(this.positionalTimer);
                    this.positionalTimer = setTimeout("$('#miniBasket .itemsClmn').animate({ top: " + desiredTop + " + 'px' }, 500, function() { self.paging = false; })", 300);
                    this.currPage = destPage;
                    this.doPageButtonVisibilities();
                    this.updateViewingItemsText();
                }
            }
            catch (err) {
            }

            ind++;
        }
    }

    this.qtyPage = Math.ceil(total_diff_items / this.qtyPerPage);
    this.totalDifferentProductsInBag = total_diff_items;

    $('#miniBasket .qty').html(this.totalQuantity.toString());

    this.doPageButtonVisibilities();
    this.updateViewingItemsText();

    $('#miniBasket  .summary div span').html(this.totalPrice);
    $('#miniBasket  .total').html(this.totalPrice);
    /*do we need this???? */
    var height = Math.min(this.products.length, this.qtyPerPage) * mini_basket_holder.itemHeight;

    $('#miniBasket .items').animate({ height: height + 'px' }, this.openSpeed);

    if (this.containsVoucher) {
        $('#miniBasket .save-for-later').css('display', 'none');
        $('#miniBasket .links .go-to-bag').addClass('gift-voucher-in-bag');
    } else {
        $('#miniBasket .save-for-later').css('display', 'block');
        $('#miniBasket .links .go-to-bag').removeClass('gift-voucher-in-bag');
    }

    if (this.products.length === 0) {
        $('#miniBasket .full').hide();
        $('#miniBasket .empty').show();
    }
    else {
        $('#miniBasket .empty').hide();
        $('#miniBasket .full').show();
    }
};

miniBasketHolder.prototype.nextPage = function() {
    if (this.paging) {
        return;
    }
    this.paging = true;
    var self = this;
    this.currPage++;
    var currentTop = parseInt($('#miniBasket .itemsClmn').css('top'), 10);
    if (isNaN(currentTop)) {
        currentTop = 0;
    }
    var newTop = currentTop - mini_basket_holder.itemContainerHeight;
    $('#miniBasket .itemsClmn').animate({ top: newTop + 'px' }, 500, function() { self.paging = false; });
    this.doPageButtonVisibilities();
    this.updateViewingItemsText();
    return false;
};

miniBasketHolder.prototype.prevPage = function() {
    if (this.paging) {
        return;
    }
    this.paging = true;
    var self = this;
    this.currPage--;
    var currentTop = parseInt($('#miniBasket .itemsClmn').css("top"), 10);
    if (isNaN(currentTop)) {
        currentTop = 0;
    }
    var newTop = currentTop + mini_basket_holder.itemContainerHeight;
    $('#miniBasket .itemsClmn').animate({ top: newTop + 'px' }, 500, function() { self.paging = false; });
    this.doPageButtonVisibilities();
    this.updateViewingItemsText();
    return false;
};

miniBasketHolder.prototype.doPageButtonVisibilities = function() {

    if (this.currPage > 1) {
        $('#miniBasket  .prev').css({ "display": "block", "background-position": "-2365px -25px" });

                $('#miniBasket  .prev').mouseover(function() {
            $('#miniBasket  .prev').css({ "display": "block", "background-position": "-2632px -25px" });
                });
                $('#miniBasket  .prev').mouseout(function() {
            $('#miniBasket  .prev').css({ "display": "block", "background-position": "-2365px -25px" });
                });

        $('#miniBasket .prev').removeClass('disabled');
    } else {
        $('#miniBasket  .prev').css({ "display": "block", "background-position": "-2899px -25px" });

                $('#miniBasket  .prev').mouseover(function() {
            $('#miniBasket  .prev').css({ "display": "block", "background-position": "-2899px -25px" });
                });
                    $('#miniBasket  .prev').mouseout(function() {
            $('#miniBasket  .prev').css({ "display": "block", "background-position": "-2899px -25px" });
                });

        $('#miniBasket .prev').addClass('disabled');

    } if (this.currPage != this.qtyPage) {
        $('#miniBasket  .next').css({ "display": "block", "background-position": "-2365px 0px" });

                $('#miniBasket  .next').mouseover(function() {
            $('#miniBasket  .next').css({ "display": "block", "background-position": "-2632px 0px" });
                });
                $('#miniBasket  .next').mouseout(function() {
            $('#miniBasket  .next').css({ "display": "block", "background-position": "-2365px 0px" });
                });

        $('#miniBasket .next').removeClass('disabled');

    } else {
        $('#miniBasket  .next').css({ "display": "block", "background-position": "-2899px 0px" });

                $('#miniBasket  .next').mouseover(function() {
            $('#miniBasket  .next').css({ "display": "block", "background-position": "-2899px 0px" });
                });
                $('#miniBasket  .next').mouseout(function() {
            $('#miniBasket  .next').css({ "display": "block", "background-position": "-2899px 0px" });
                });

        $('#miniBasket .next').addClass('disabled');
    }
};

miniBasketHolder.prototype.updateViewingItemsText = function() {
    var startNumber = ((this.currPage - 1) * this.qtyPerPage) + 1;
    var endNumber = Math.min((this.currPage * this.qtyPerPage), this.totalDifferentProductsInBag);
    $('#viewingItemsText').text("Your Bag Items: " + this.totalQuantity);
};

miniBasketHolder.prototype.doError = function(errorMessage) {
    $('#miniBasketError').html(errorMessage);
    $('#miniBasketError').show();
    $(".add-to-bag-notification").html("");
    mini_basket_holder.maximizeBasket(true);
    this.errorMessageHideTimeout = setTimeout(function() {
        $('#miniBasketError').hide();
    }, mini_basket_holder.productAddedTimeout);
};

miniBasketHolder.prototype.maximizeBasket = function(notInvokedDirectlyByUser) {
    if (this.minimizing) {
        return;
    }

    this.maximized = true;

    $('#miniBasket').addClass("sel");

        $('#miniBasket .mini-bag-wrapper').slideDown(this.openSpeed);

    $('#miniBasket .top').slideDown(miniBasketHolder.openSpeed);
    var self = this;

    $('#miniBasket').hover(
        function() {
            clearTimeout(this.minimiseBasketTimeout);
        },
        function() {
            clearTimeout(this.minimiseBasketTimeout);
            this.minimiseBasketTimeout = setTimeout(function() { self.minimizeBasket(); }, self.minimizeAfterMouseLeaveTimeout);
        }
    );
    clearTimeout(this.minimiseBasketTimeout);
    if (notInvokedDirectlyByUser) {
        this.minimiseBasketTimeout = setTimeout(function() { self.minimizeBasket(); }, this.minimizeAfterAddTimeout);
    }
};

miniBasketHolder.prototype.resetMinimiseAfterClick = function() {
    var self = this;
    clearTimeout(this.minimiseBasketTimeout);
    this.minimiseBasketTimeout = setTimeout(function() { self.minimizeBasket(); }, self.minimizeAfterAddTimeout);
};

miniBasketHolder.prototype.minimizeBasket = function() {
    if (!this.maximized || this.isMouseOverMiniBasket) {
        return;
    }
    this.maximized = false;
    this.minimizing = true;
    $('#miniBasket .mini-bag-wrapper').slideUp(this.closeSpeed);
    $('#miniBasket .top').slideUp(this.closeSpeed);
    var self = this;
    setTimeout(function() { $('#miniBasket').removeClass("sel"); self.minimizing = false; }, 500);
};

mini_basket_holder = new miniBasketHolder();
